package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.User;
import com.baosight.sczx.common.zm.cInterface.cm.Depot;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMImportMaterial;
import com.baosight.sczx.zm.cm.domain.ZMCMImportmaterialDetail;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;


/**
 * 材料使用管理-物资入库管理-入库单
 * <p>Title: ServiceZMCMB0.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 杨鸣
 * @version 1.0
 * <pre>Histroy:
 *          2011-6-30 下午02:37:53  杨鸣  Create
 *</pre>
 */

public class ServiceZMCMB0 extends ServiceEPBase {

	/**初始数据
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMB0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-5-30 上午09:49:43  杨鸣
	 * </p>
	 *
	*/
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		EiInfo outInfo = this.query(inInfo);
		outInfo.set("depotName", Depot.getDepots().get(0).getFdDepotName());//库房名称默认填入库房管理中建立的一级库房
		outInfo.set("userId", UserSession.getUserId());//用户Id默认填入库确认人
		outInfo.set("userName", UserSession.getInSessionProperty("UserCname"));//用户Name默认填入库确认人
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.units"));
		outInfo.addBlock(User.getInstance().getConstructionStaff(false));
		outInfo.addBlock(generateImportType());
		return outInfo;
	}

	/**列表查询
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMB0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-5-30 上午09:49:43  杨鸣
	 * </p>
	 *
	*/
	@Override
	public EiInfo query(EiInfo inInfo) {
		EiInfo outInfo = super.query(inInfo, "ZMCMImportMaterial.query", new ZMCMImportMaterial());
		return outInfo;
	}
	
	/**
	 * 
	 * <p>Function: generateImportType</p>
	 * <p>Description: </p>
	 * <p>return value:EiBlock</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:28:08 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private EiBlock generateImportType()
	{
		EiBlock block = new EiBlock("cmes.cm.queryImportType");
		EiColumn column = new EiColumn("value");
		column.setDescName("值");
		block.getBlockMeta().addMeta(column);
		
		column = new EiColumn("display");
		column.setDescName("名称");
		block.getBlockMeta().addMeta(column);
		
		Map inMap = new HashMap();
		inMap.put("value", "");
		inMap.put("display", "");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "一般入库");
		inMap.put("display", "一般入库");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "估收入库");
		inMap.put("display", "估收入库");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "超前入库");
		inMap.put("display", "超前入库");
		block.addRow(inMap);
		
		inMap = new HashMap();
		inMap.put("value", "红冲");
		inMap.put("display", "红冲");
		block.addRow(inMap);
		
		return block;
	}

	/**
	 * <p>Function: insert</p>
	 * <p>Description: 红冲入库</p>
	 * <p>return value: ServiceZMCMB0</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-28下午02:18:16 张小飞
	 *    2011-9-8		modified by wangkun
	 * </p>
	 *
	*/
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{
		String fdImportType = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdImportType");
		if(validateTypeManagement(inInfo))
		{
			return inInfo;
		}
		
		//校验选中入库单是否已经红冲
		if(hasMinus(inInfo, "红冲"))
		{
			return inInfo;
		}
		
		int result_int = MaterialBase.isInAccountDate(inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdNoteDate"));
		if(result_int == -2 || result_int == 0)
		{
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("选中记录的单据日期已经超出" + MaterialBase.getAccountDate(StaticTools.getDate())[2] + "月的记账范围，不能办理红冲！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		
		//校验红冲明细的数量是否大于库存里的数量
		boolean isExceed = isExceed(inInfo, "红冲", fdImportType);
		if(isExceed) 
		{
			return inInfo;
		}
		else
		{
			String fdKeyId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdKeyId");

			
			boolean result = minusImport(inInfo, fdKeyId);	//红冲入库单
			
			if(!result)
			{
				return inInfo;
			}
			
			minusBaseMeterial(inInfo, fdKeyId, fdImportType);		//红冲库存材料
			
			return this.query(inInfo);
		}
	}
	
	/**
	 * 
	 * <p>Function: validateTypeManagement</p>
	 * <p>Description: 校验是否有选中物资的分管权限</p>
	 * <p>return value:boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-11-3下午01:51:26 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean validateTypeManagement(EiInfo inInfo)
	{
		List link = new ArrayList();
		String oldKeyId =  inInfo.getBlock("result").getCellStr(0, "fdKeyId");//主键
        
		Map inMap = new HashMap();
		String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
		String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
		if(isUseTypeManagement.equals("1"))
		{
			inMap.put("fdImportPeopleId", UserSession.getUserId());
			List _list = dao.query(sqlmap, inMap);
			link = Utils.generateValidateData(_list);
		}
		else
		{
			sqlmap = "ZMCMMaterialType.type";
			
			List _list = dao.query(sqlmap, inMap);
    		
			for(int i = 0; i<_list.size(); i++)
			{
				Map _map = (Map)_list.get(i);
				link.add(_map.get("fdTypeCode").toString());
			}
		}
        
		Map<String, String> _map = new HashMap();
		_map.put("fdImportmaterialId", oldKeyId);
		List<ZMCMImportmaterialDetail> list = dao.query("ZMCMImportmaterialDetail.query",_map);	
		
		for(int j=0; j<list.size(); j++)
		{
			ZMCMImportmaterialDetail detail = list.get(j);
			String materialCode = detail.getFdMaterialCode();
			boolean flag = false;
			for(int k=0; k<link.size(); k++)
			{
				if(materialCode.startsWith(link.get(k).toString()))
				{
					flag = true;
				}
			}
			
			if(!flag)
			{
				inInfo.setStatus(-1);
				inInfo.setMsg("当前登录用户不具有该入库单中部分物资的分管权限，不允许红冲！");
				return true;
			}
		}
		
		return false;
	}
	
	/**
	 * 
	 * <p>Function: hasMinus</p>
	 * <p>Description: 是否已红冲</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-13上午10:35:50 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean hasMinus(EiInfo inInfo, String operationString)
	{
		String fdNoteCode = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdNoteCode");
		String fdImportType = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdImportType");
		
		Map _map = new HashMap();
		_map.put("fdResourceNoteCode", fdNoteCode);
		_map.put("fdImportType", fdImportType);
		
		List<ZMCMImportmaterialDetail> _list = dao.query("ZMCMImportMaterial.validate", _map);
		
		if(_list.size() > 0)
		{
			inInfo.setStatus(-1);
			inInfo.setMsg("选中的入库单已" + operationString + "，不允许再次" + operationString + "！");
			return true;
		}
		
		return false;
	}
	
	/**
	 * 
	 * <p>Function: isExceed</p>
	 * <p>Description: 验证是否大于库存数量</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-8上午10:11:32 modified by bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean isExceed(EiInfo inInfo, String operationString, String fdImportType) 
	{
		String fdKeyId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdKeyId");
		Map _map = new HashMap();
		_map.put("fdImportmaterialId", fdKeyId);
		List<ZMCMImportmaterialDetail> _list = dao.query("ZMCMImportmaterialDetail.canHCRK", _map);
		if(_list != null && !_list.isEmpty())
		{
			for(ZMCMImportmaterialDetail detail : _list)
			{
				Double num=0.0;
				if("一般入库".equals(fdImportType))
				{
					num = detail.getFdHasinvoiceNum()==null?0.0:detail.getFdHasinvoiceNum();
				}
				else if("估收入库".equals(fdImportType))
				{
					num = detail.getFdNoinvoiceNum();
				}
				else
				{
					num = detail.getFdNum()-detail.getFdNoinvoiceNum()-
						(detail.getFdHasinvoiceNum()==null?0.0:detail.getFdHasinvoiceNum());
				}
				
				if(detail.getFdActualNumber() > num)
				{
					inInfo.setStatus(-1);
					StringBuffer msg = new StringBuffer(operationString + "失败，");
					msg.append("物资编码为："+detail.getFdMaterialCode());
					msg.append("的入库单据，" + operationString + 
								"数量大于库存中现有物资的数量，不允许" + operationString + "该单据！");
					inInfo.setMsg(msg.toString());
					return true;
				}
			}
		}
		
		return false;
	}
	
	/**
	 * 
	 * <p>Function: minusImport</p>
	 * <p>Description: 生成红冲入库单</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-8上午11:01:54 bobswang
	 * </p>
	 *
	 */
	private boolean minusImport(EiInfo inInfo, String oldFdKeyId)
	{
		boolean result = false;
		
		String fdKeyId = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL");
		String resourceNoteCode = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdNoteCode");
		String NoteDate = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdNoteDate");
		
		inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdKeyId", fdKeyId);
		inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdResourceNoteCode", resourceNoteCode);
		if(resourceNoteCode.length() > 27)
		{
			inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdNoteCode", "HC_"+resourceNoteCode.substring(0, 27));
		}
		else
		{
			inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdNoteCode", "HC_"+resourceNoteCode);
		}
		inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdImportType", "红冲");
		inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdYear", MaterialBase.getAccountDate(NoteDate)[0]);
		inInfo.getBlock(EiConstant.resultBlock).setCell(0, "fdMonth", MaterialBase.getAccountDate(NoteDate)[1]);
		
		EiInfo resultInfo = super.insert(inInfo, "ZMCMImportMaterial.insert");
		
		if(resultInfo.getStatus() != -1)
		{
			minusImportDetail(inInfo, oldFdKeyId);
			return true;
		}
		else
		{
			inInfo.setStatus(-1);
			inInfo.addMsg(resultInfo.getMsg());
		}
		
		return result;
	}
	
	/**
	 * 
	 * <p>Function: minusImportDetail</p>
	 * <p>Description: 红冲入库明细</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-8上午11:03:01 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void minusImportDetail(EiInfo inInfo, String oldFdKeyId)
	{		
		String fdPrimaryKeyId = inInfo.getBlock(EiConstant.resultBlock).getCellStr(0, "fdKeyId");
		
		Map _map = new HashMap();
		_map.put("fdImportmaterialId", oldFdKeyId);
		List<ZMCMImportmaterialDetail> _list = dao.query("ZMCMImportmaterialDetail.canHCRK", _map);
		if(_list != null && !_list.isEmpty())
		{
			for(ZMCMImportmaterialDetail detail : _list)
			{
				String fdKeyId = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL_DETAIL");
				
				//构造与原单数量相同的负的明细
				Map inMap = new HashMap();
				inMap.put("fdKeyId", fdKeyId);
				inMap.put("fdImportmaterialId", fdPrimaryKeyId);
				inMap.put("fdProvideDepartment", detail.getFdProvideDepartment());
				inMap.put("fdMaterialSource", detail.getFdMaterialSource());
				inMap.put("fdInvoice", detail.getFdInvoice());
				inMap.put("fdMaterialId", detail.getFdMaterialId());
				inMap.put("fdMaterialCode", detail.getFdMaterialCode());
				inMap.put("fdMaterialName", detail.getFdMaterialName());
				inMap.put("fdSpecModel", detail.getFdSpecModel());
				inMap.put("fdNumber", detail.getFdNumber());
				inMap.put("fdQuality", detail.getFdQuality());
				inMap.put("fdStatus", detail.getFdStatus());
				inMap.put("fdReduceNumber", detail.getFdReduceNumber());
				inMap.put("fdMetric", detail.getFdMetric());
				inMap.put("fdSum", (0-detail.getFdSum())+"");
				inMap.put("fdPrice", detail.getFdPrice());
				inMap.put("fdPlanNumber", (0-detail.getFdPlanNumber())+"");
				inMap.put("fdActualNumber", (0-detail.getFdActualNumber())+"");
				inMap.put("fdConfirmPeople", detail.getFdConfirmPeople());
				inMap.put("fdInvoiceSum", "0");
				inMap.put("fdRemark", detail.getFdRemark());
				
				//插入新的负入库明细
				dao.insert("ZMCMImportmaterialDetail.insert", inMap);
				
				inMap = new HashMap();
				inMap.put("fdReduceNumber", detail.getFdActualNumber()+"");
				inMap.put("fdStatus", "全部");
				inMap.put("fdKeyId", detail.getFdKeyId());
				
				//更新原单据的已冲数量
				dao.update("ZMCMImportmaterialDetail.updateReduceNum", inMap);
			}
		}
	}
	
	/**
	 * 
	 * <p>Function: minusBaseMeterial</p>
	 * <p>Description: 红冲库存材料</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-8上午11:03:01 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void minusBaseMeterial(EiInfo inInfo, String oldFdKeyId, String fdImportType)
	{
		Map _map = new HashMap();
		_map.put("fdImportmaterialId", oldFdKeyId);
		List<ZMCMImportmaterialDetail> _list = dao.query("ZMCMImportmaterialDetail.query", _map);
		if(_list != null && !_list.isEmpty())
		{
			for(ZMCMImportmaterialDetail detail : _list)
			{
				//修改库存中物资数量、金额等
				Map inMap = new HashMap();
				inMap.put("fdMaterialId", detail.getFdMaterialId());
				
				List<ZMCMMaterialBase> base_list = dao.query("ZMCMMaterialBase.query", inMap);
				ZMCMMaterialBase material = base_list.get(0);
				
				inMap.put("fdNum", (material.getFdNum() - detail.getFdActualNumber())+"");
				inMap.put("fdSum", BigDecimal.valueOf((material.getFdNum() - detail.getFdActualNumber())*material.getFdPrice())+"");
				inMap.put("fdPrice", material.getFdPrice()+"");
				inMap.put("fdLastImportDate", material.getFdLastImportDate());
				
				if(detail.getFdInvoiceSum() == null)
				{
					inMap.put("fdActualSum", BigDecimal.valueOf(material.getFdActualSum() - detail.getFdSum()));
				
					if((material.getFdNum() - detail.getFdActualNumber()) != Double.parseDouble("0"))
					{
						inMap.put("fdActualPrice", BigDecimal.valueOf((material.getFdActualSum() - detail.getFdSum())/(material.getFdNum() - detail.getFdActualNumber())));
					}
					else
					{
						inMap.put("fdActualPrice", detail.getFdPrice());
					}					
				}
				else
				{
					inMap.put("fdActualSum", BigDecimal.valueOf(material.getFdActualSum() - detail.getFdInvoiceSum()));
				
					if((material.getFdNum() - detail.getFdActualNumber()) != Double.parseDouble("0"))
					{
						inMap.put("fdActualPrice", BigDecimal.valueOf((material.getFdActualSum() - detail.getFdInvoiceSum())/(material.getFdNum() - detail.getFdActualNumber())));
					}
					else
					{
						inMap.put("fdActualPrice", detail.getFdPrice());
					}
				}
				
				if("一般入库".equals(fdImportType))
				{
					inMap.put("fdHasinvoiceNum", (material.getFdHasinvoiceNum() - detail.getFdActualNumber())+"");
					inMap.put("fdNoinvoiceNum", material.getFdNoinvoiceNum()+"");
				}
				else if("估收入库".equals(fdImportType))
				{
					inMap.put("fdHasinvoiceNum", material.getFdHasinvoiceNum()+"");
					inMap.put("fdNoinvoiceNum", (material.getFdNoinvoiceNum() - detail.getFdActualNumber())+"");
				}
				else
				{
					inMap.put("fdHasinvoiceNum", material.getFdHasinvoiceNum()+"");
					inMap.put("fdNoinvoiceNum", material.getFdNoinvoiceNum()+"");
				}
				
				dao.update("ZMCMMaterialBase.updateAfterStorage", inMap);
			}
		}
	}
}
